package com.alogic.swagger.core;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsArray;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonArray;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Operation
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class SwaggerOperation extends Segment {
    private String method = "get";

    private String $summary;
    private String $desc;
    private String $operationId;
    private String $deprecated;
    private String $tags;

    public SwaggerOperation(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        method = PropertiesConstants.getString(p,"method",method,true);
        $summary = PropertiesConstants.getRaw(p,"summary","");
        $tags = PropertiesConstants.getRaw(p,"tags","");
        $desc = PropertiesConstants.getRaw(p,"description","");
        $operationId = PropertiesConstants.getRaw(p,"opreationId","");
        $deprecated = PropertiesConstants.getRaw(p,"deprecated","");
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        XsObject newOperation = current.getObjectChild(method,true);
        newOperation.addProperty("summary",PropertiesConstants.transform(ctx,$summary,""));
        newOperation.addProperty("description",PropertiesConstants.transform(ctx,$desc,""));
        newOperation.addProperty("opreationId",PropertiesConstants.transform(ctx,$operationId,""));
        newOperation.addProperty("deprecated",PropertiesConstants.transform(ctx,$deprecated,false));

        String [] tags = PropertiesConstants.transform(ctx,$tags,"").split(",");
        if (tags.length > 0){
            XsArray array = newOperation.getArrayChild("tags",true);
            if (array instanceof JsonArray){
                JsonArray jsonArray = (JsonArray)array;
                @SuppressWarnings("unchecked")
                List<Object> content = (List<Object>)jsonArray.getContent();
                for (String tag:tags){
                    if (StringUtils.isNotEmpty(tag)){
                        content.add(tag);
                    }
                }
            }
        }

        super.onExecute(root, newOperation, ctx, watcher);
    }
}